package MyUtil;

import javax.swing.*;
import java.io.*;
import java.sql.*;
import java.util.Properties;
public class DataBaseUtil {
    private static Connection conn;
    private DataBaseUtil(){
    }
    public static Connection GetConnection(){
        if(conn==null){
            Properties properties = new Properties();
            try{
                properties.load(new FileInputStream("Login.properties"));
                String account = properties.getProperty("account");
                String password = properties.getProperty("password");
                Class.forName("oracle.jdbc.driver.OracleDriver");
                conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",account,password);

            }catch(ClassNotFoundException | SQLException | FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return conn;
    }

    public static ResultSet produceResultSet(String sql) throws SQLException {
        Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
        ResultSet ts = stmt.executeQuery(sql);
        return ts;
    }

    public static ResultSet prepareResultSet(String sql, Object... objects) throws SQLException {// ... 不定量
        PreparedStatement p1 = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
        int i = 1;
        for(Object o1:objects){
            p1.setObject(i++,o1);
        }
        ResultSet ts = p1.executeQuery();
        return ts;
    }
    public static void changeResultSet(String sql, Object... objects) throws SQLException {// ... 不定量
        PreparedStatement p1 = conn.prepareStatement(sql);
        int i = 1;
        for(Object o1:objects){
            p1.setObject(i++,o1);
        }
        int ts = p1.executeUpdate();
        conn.commit();
        JOptionPane.showMessageDialog(null,"已完成"+ts+"项修改");
        p1.close();
    }



    public static void closeConnection() throws SQLException {
        if (conn != null) {
            conn.close();
        }
    }
}
